import os
import requests
import hashlib
import zipfile


def md5_code(passwd):  # 给密码加密（使用md5工具）
    md5 = hashlib.md5()
    md5.update(passwd.encode("utf-8"))
    return md5.hexdigest()


def trans_str(s):  # 转换str（要通过包含的方式去断言,将":"和":转换成=号）
    s = s.replace('":"', "=").replace('":', '=')
    return s


def zip_dir(startdir, zip_file):  # 压缩文件，只要给文件夹的路径，以及压缩过后的文件名字（在mail中使用）
    # 压缩文件夹
    _zip_file = os.path.join(startdir, zip_file)
    if os.path.exists(_zip_file):
        # 先删除
        os.remove(_zip_file)
    z = zipfile.ZipFile(_zip_file, 'w', zipfile.ZIP_DEFLATED)
    for dir_path, dir_names, file_names in os.walk(startdir):
        fpath = dir_path.replace(startdir, '')  # 不replace的话, 就从根目录开始复制
        fpath = fpath and fpath + os.sep or ''
        for filename in file_names:
            z.write(os.path.join(dir_path, filename), fpath + filename)
    z.close()


def user_register():  # 新会员注册
    url = "http://hn216.api.yesapi.cn/api/App/User/RegisterExt"
    payload = {
        "app_key": "7082404251B51D1102100638B6E84E5A",
        "username": "张磊88",
        "password": "wxy113014"
    }
    r = requests.post(url=url, data=payload)


def user_login():  # 新会员登录
    url = "http://hn216.api.yesapi.cn/api/App/User/LoginExt"
    payload = {
        "app_key": "7082404251B51D1102100638B6E84E5A",
        "username": "张磊88",
        "password": "wxy113014"
    }
    r = requests.post(url=url, data=payload)
    body = r.json()
    token = body.get("data").get("token")
    uuid = body.get("data").get("uuid")
    return token, uuid  # 拿到token和uuid


def user_login_get_message_num():  # 要获取到新消息数量必须先登录
    url = "http://hn216.api.yesapi.cn/api/App/User/LoginExt"
    payload = {
        "app_key": "7082404251B51D1102100638B6E84E5A",
        "username": "张磊3",
        "password": "wxy113014"
    }
    r = requests.post(url=url, data=payload)
    body = r.json()
    token = body.get("data").get("token")
    return token